package cc.z8g.browser.utils;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.webkit.WebView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;

import java.net.URISyntaxException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cc.z8g.browser.R;
import cc.z8g.browser.core.BrowserConst;

public final class IntentUtils {


    private static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile("(?i)"
            + // switch on case insensitive matching
            '('
            + // begin group for schema
            "(?:http|https|file)://" + "|(?:inline|data|about|javascript):" + "|(?:.*:.*@)"
            + ')' + "(.*)");

    public static boolean startActivityForUrl(@NonNull Activity activity, @Nullable WebView tab, @NonNull String url) {
        Intent intent;
        try {
            intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
        } catch (URISyntaxException ex) {
            Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
            return false;
        }

        intent.addCategory(Intent.CATEGORY_BROWSABLE);
        intent.setComponent(null);
        intent.setSelector(null);

        if (activity.getPackageManager().resolveActivity(intent, 0) == null) {
            String packagename = intent.getPackage();
            if (packagename != null) {
                intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pname:" + packagename));
                intent.addCategory(Intent.CATEGORY_BROWSABLE);
                activity.startActivity(intent);
                return true;
            } else {
                return false;
            }
        }
        if (tab != null) {
            intent.putExtra(BrowserConst.INTENT_ORIGIN, tab.hashCode());
        }

        Matcher m = ACCEPTED_URI_SCHEMA.matcher(url);
        if (m.matches()) { //  && !isSpecializedHandlerAvailable(activity, intent)
            return false;
        }
        try {
            if (activity.startActivityIfNeeded(intent, -1)) {
                return true;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return false;
    }

    /**
     * Shares a URL to the system.
     *
     * @param url   the URL to share. If the URL is null or a special URL, no sharing will occur.
     * @param title the title of the URL to share. This is optional.
     */
    public static void shareUrl(FragmentActivity activity, @Nullable String url, @Nullable String title) {
        if (url != null && !UrlUtils.isInnerUrl(url)) {
            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("text/plain");
            if (title != null) {
                shareIntent.putExtra(Intent.EXTRA_SUBJECT, title);
            }
            shareIntent.putExtra(Intent.EXTRA_TEXT, url);
            activity.startActivity(Intent.createChooser(shareIntent, activity.getString(R.string.dialog_title_share)));
        }
    }

    /** 打开普通窗口/打开无痕模式窗口 */
    public static void launchActivity(@NonNull Activity src, @NonNull Class<? extends Activity> dstType, @Nullable String url) {
        Intent intent = new Intent(src, dstType);
        Uri uri = url == null ? null : Uri.parse(url);
        intent.setData(uri);
        src.startActivity(intent);
    }

    /** 创建一个意图，用来启动电子邮件应用程序 */
    @NonNull
    public static Intent newEmailIntent(String address, String subject, String body, String cc) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.putExtra(Intent.EXTRA_EMAIL, new String[]{address});
        intent.putExtra(Intent.EXTRA_TEXT, body);
        intent.putExtra(Intent.EXTRA_SUBJECT, subject);
        intent.putExtra(Intent.EXTRA_CC, cc);
        intent.setType("message/rfc822");
        return intent;
    }
}
